$(function () {
    function init() {
        queryHospitalCount();
        queryLoadRate();
        queryAssets();
        queryPersonTimes();
        queryHospitalDistribution();
        queryMap();
    }
    /* 医院总数 */
    function queryHospitalCount() {
        publicAjax(basePath + 'charts/area/overview/level', 'post', null, function (data) {
            var list = data.data.list || [];
            var str = '',
                hospitalCount = 0;
            for (var i = 0; i < list.length; i++) {
                str += '<p><span class="level-count">'+ fix0(list[i].hospitalCounts) +'</span>' +
                    '<span>'+ list[i].name +'&nbsp;门诊量：' + fix0(list[i].outpatientCounts) + '人次</span>';
                hospitalCount += fix0(list[i].hospitalCounts);
            }
            $('#hospital-count').text(hospitalCount);
            $('#hospital-counts').html(str);
        });
    }
    /* 负荷率 */
    var chartLoadRate = echarts.init($('#load-rate-chart')[0]);
    function queryLoadRate() {
        chartLoadRate.setOption(optionLoadRate);
    }
    /* 设备情况 */
    var chartAssets = echarts.init($('#assets-chart')[0]);
    function queryAssets () {
        publicAjax(basePath + 'charts/area/overview/type-risk', 'post', null, function (data) {
            var type = data.data.type || [];
            for (var i = 0; i < type.length; i++) {
                optionAssets.series[0].data[i].name = type[i].name;
                optionAssets.series[0].data[i].value = fix2(type[i].curPrice / PRICE_CONVERT);
            }
            var risk = data.data.risk || [];
            for (var i = 0; i < risk.length; i++) {
                optionAssets.series[1].data[i].name = risk[i].name;
                optionAssets.series[1].data[i].value = fix2(risk[i].price / PRICE_CONVERT);
            }
            // 悬浮显示
            optionAssets.tooltip.formatter = function (params) {
                var index = params.dataIndex;
                if (params.seriesIndex === 0) {
                    return type[index].name + '<br/>' +
                        '设备金额：' + fix2(type[index].curPrice / PRICE_CONVERT) + '万元<br/>' +
                        '设备数量：' + fix0(type[index].curCounts) + '台';
                } else {
                    return risk[index].name + '<br/>' +
                        '设备金额：' + fix2(risk[index].price / PRICE_CONVERT) + '万元<br/>' +
                        '设备数量：' + fix0(risk[index].counts) + '台';
                }
            };
            // Label显示 设备金额
            optionAssets.series[0].label.normal.formatter = function (params) {
                if (params.dataIndex === 1) {
                    return '设备金额';
                } else if (params.dataIndex === 3) {
                    return fix2(data.data.total.curPrice / PRICE_CONVERT) + '万元';
                } else {
                    return '';
                }
            };
            chartAssets.setOption(optionAssets);
            // 设备数量
            $('#assets-count').text(Math.abs(fix0(data.data.total.curCounts)) + '台')
                .next('img').attr('href',
                    data.data.total.countsYoY >= 0
                        ? basePath + 'plugins/charts/images/arrow_up.png'
                        : basePath + 'plugins/charts/images/arrow_down.png'
                );
            $('#key-point-assets').text(fix0(data.data.total.curKeyPointCounts) + '台');
        });
    }

    /* 服务人次 */
    var chartPersonTimes = echarts.init($('#person-chart')[0]);
    function queryPersonTimes () {
        publicAjax(basePath + 'charts/area/overview/service-pie', 'post', null, function (data) {
            var list = data.data.list || [];
            var personCount = 0;
            for (var i = 0; i < list.length; i++) {
                optionPersonTimes.series[0].data[i].name = list[i].name;
                optionPersonTimes.series[0].data[i].value = fix0(list[i].curDayUsedCounts);
                personCount += fix0(list[i].curDayUsedCounts);
            }
            optionPersonTimes.tooltip.formatter = function (params) {
                var index = params.dataIndex;
                return list[index].name + '<br/>' +
                    '设备金额：' + fix2(list[index].curPrice / PRICE_CONVERT) + '万元<br/>' +
                    '设备数量：' + fix0(list[index].curCounts) + '台<br/>' +
                    '总服务人次：' + fix0(list[index].curUsedCounts) + '人<br/>' +
                    '服务人次同比：' + fix2(list[index].usedCountsYoy) + '%<br/>' +
                    '门诊服务人次：' + fix0(list[index].curOutpatientCounts) + '人<br/>' +
                    '住院服务人次：' + fix0(list[index].curHospitalizedCounts) + '人<br/>' +
                    '当日服务人次：' + fix0(list[index].curDayUsedCounts) + '人';
            };
            optionPersonTimes.series[0].label.normal.formatter = function (params) {
                if (params.dataIndex === 1) {
                    return '当日人次';
                } else if (params.dataIndex === 3) {
                    return personCount + '人';
                } else {
                    return '';
                }
            };
            chartPersonTimes.setOption(optionPersonTimes);
            var total = data.data.total || {};
            $('#person-count').text(fix0(total.curUsedCounts))
                .next('img').attr('href',
                data.data.total.usedCountsYoy >= 0
                    ? basePath + 'plugins/charts/images/arrow_up.png'
                    : basePath + 'plugins/charts/images/arrow_down.png'
            );
            $('#inpatient-assets').text(fix0(total.curDayUsedCounts));
        });
    }

    /* 医院服务人次列表接口(柱状折线图,排名,更多) */
    var topData = [];  // 排名数据
    var chartHospitalDistribution = echarts.init($('#hospital-distribution')[0]);
    function queryHospitalDistribution () {
        publicAjax(basePath + 'charts/area/overview/service-list', 'post', null, function (data) {
            var list = data.data.list || [];
            topData[0] = list.calTotal();
            optionHospital.xAxis[0].data = [];
            optionHospital.series[0].data = [];
            optionHospital.series[1].data = [];
            optionHospital.series[2].data = [];
            for (var i = 0; i < list.length; i++) {
                optionHospital.xAxis[0].data.push(list[i].name);
                optionHospital.series[0].data.push(fix2(list[i].curPrice / PRICE_CONVERT));
                optionHospital.series[1].data.push(fix0(list[i].curOutpatientCounts));
                optionHospital.series[2].data.push(fix0(list[i].curHospitalizedCounts));
            }
            optionHospital.tooltip.formatter = function (params) {
                var index = params[0].dataIndex;
                return list[index].name + '<br/>' +
                    '设备金额：' + fix2(list[index].curPrice / PRICE_CONVERT) + '万元<br/>' +
                    '设备数量：' + fix0(list[index].curCounts) + '台<br/>' +
                    '总服务人次：' + fix0(list[index].curUsedCounts) + '人<br/>' +
                    '服务人次同比：' + fix2(list[index].usedCountsYoy) + '%<br/>' +
                    '门诊服务人次：' + fix0(list[index].curOutpatientCounts) + '人<br/>' +
                    '住院服务人次：' + fix0(list[index].curHospitalizedCounts) + '人';
            };
            chartHospitalDistribution.setOption(optionHospital);
            setTop(0, '', 'desc');
        });
    }

    /* 闵行区地图 */
    var chartMap = echarts.init($('#map')[0]);
    function queryMap () {
        $.getJSON(basePath + '/js/area/minhang.json', function (geoJson) {
            echarts.registerMap('minhang', geoJson);
            // myChart.hideLoading();
            publicAjax(basePath + 'charts/area/overview/map', 'post', null, function (data) {
                var totalAmountArr = [];
                var screens = data.data.list || [];
                var data = [];
                for (var i = 0; i < screens.length; i++) {
                    if (screens[i].mapX && screens[i].mapY) {
                        data.push({
                            name: screens[i].hospitalName,
                            /* 经度，纬度 */
                            value: [screens[i].mapX, screens[i].mapY]
                        });
                        totalAmountArr.push(0);
                    }
                }
                optionMap.series[0].data = data;
                optionMap.series[0].sampleSize = function (data) {
                    var max = totalAmountArr.max(),
                        min = totalAmountArr.min(),
                        range = max - min;
                    if (range === 0) return 35;
                    return data[2] === 0 ? 20 : (30 * (data[2] - min) / range + 20);
                };
                chartMap.clear();
                chartMap.setOption(optionMap);
            });
        });
    }

    /* 设置排名 */
    function setTop(tag, key, sorting) {// 0-设备   1-维修  2-保养   3-巡检
        loading();
        var list = $.extend([], topData[tag]).sortByKey(sorting, key);
        var topStr = '',
            theadStr = '',
            tbodyStr = '',
            tfootStr = '',
            table = $('#detail-table'),
            thead = table.find('thead'),
            tbody = table.find('tbody'),
            tfoot = table.find('tfoot');
        if (tag === 0) {
            for (var i = 0; i < topData[tag].length; i++) {
                topStr += '<p>' +
                    '<span class="name">' + topData[tag][i].name + '</span>' +
                    '<span class="value">' + fix0(topData[tag][i].curCounts) + '</span>' +
                    '<span class="value">' + fix0(topData[tag][i].curUsedCounts) + '</span>' +
                    '</p>'
                tbodyStr += (
                    '<tr>' +
                    '<td class="tc">' + (i + 1) + '</td>' +
                    '<td $class="spanTitle" $onclick="query(\'' + tag + '\',\'' + list[i].id + '\')">' + fixStr(list[i].name) + '</td>' +
                    '<td class="tr">' + fix2(list[i].curPrice / PRICE_CONVERT) + '</td>' +
                    '<td class="tr">' + fix0(list[i].curCounts) + '</td>' +
                    '<td class="tr">' + fix0(list[i].curUsedCounts) + '</td>' +
                    '<td class="tr">' + fix2(list[i].usedCountsYoy) + '</td>' +
                    '<td class="tr">' + fix0(list[i].curOutpatientCounts) + '</td>' +
                    '<td class="tr">' + fix0(list[i].curHospitalizedCounts) + '</td>' +
                    '</tr>'
                );
            }
            theadStr = (
                '<tr><th class="tc">#</th>' +
                '<th class="sort tl" data-key="name">医院名称</th>' +
                '<th class="sort tr" data-key="curPrice">设备金额(万元)</th>' +
                '<th class="sort tr" data-key="curCounts">设备数量(台)</th>' +
                '<th class="sort tr" data-key="curUsedCounts">总服务人次</th>' +
                '<th class="sort tr" data-key="usedCountsYoy">服务人次同比(%)</th>' +
                '<th class="sort tr" data-key="curOutpatientCounts">门诊服务人次</th>' +
                '<th class="sort tr" data-key="curHospitalizedCounts">住院服务人次</th>' +
                '</tr>'
            );
            tfootStr = (
                '<tr>' +
                '<td class="tc">'+$.i18n.prop('share.table.tail.zj')+'</td>' +
                '<td class="tl">' + list.length + '</td>' +
                '<td class="tr">' + fix2(list[-1].curPrice / PRICE_CONVERT) + '</td>' +
                '<td class="tr">' + fix0(list[-1].curCounts) + '</td>' +
                '<td class="tr">' + fix0(list[-1].curUsedCounts) + '</td>' +
                '<td class="tr">' + fix2(list[-1].usedCountsYoy/ list.length) + '</td>' +
                '<td class="tr">' + fix0(list[-1].curOutpatientCounts) + '</td>' +
                '<td class="tr">' + fix0(list[-1].curHospitalizedCounts) + '</td>' +
                '</tr>'
            );
        }
        $('#value').html(topStr);
        thead.html(theadStr);
        tbody.html(tbodyStr);
        tfoot.html(tfootStr);
        /* 排序 */
        // 添加排序图片
        var sort = thead.find('.sort').append('<img src="' + basePath + 'plugins/charts/images/sort.png">').each(function () {
            if (key === $(this).data().key) { // 根据sorting和key设置排序字段图片
                $(this).find('img').attr('src', basePath + 'plugins/charts/images/sort_' + (sorting === 'desc' ? 'up' : 'down') + '.png');
            }
        });
        /* 点击表头重新排序 */
        sort.on('click', function () {
            var src = $(this).find('img').attr('src');
            if (src.indexOf('sort_up.png') !== -1) {
                setTop(tag, $(this).data().key, 'asc');
            } else if ((src.indexOf('sort_down.png') !== -1) || (src.indexOf('sort.png') !== -1)) {
                setTop(tag, $(this).data().key, 'desc');
            }
        });
        // 延时设置表格首尾固定，防止页面卡死
        setTimeout(function () {
            // 如果列表长度大于200，则值固定表头表尾，不固定前两列，防止页面卡死
            if (list.length > 200) {
                table.tableHeadFixer({'head': true, 'foot': true});
            } else {
                table.tableHeadFixer({'left': 2, 'head': true, 'foot': true});
            }
            loading(true);
        }, 20);
    }

    /* 初始化详情模态框 */
    var hospitalModal = $('#hospital-modal');
    hospitalModal.iziModal({
        title: '医院排名',
        headerColor: '#222431',
        width: '100%',
        radius: 3,
        zindex: 80,
        history: false,
        bodyOverflow: true,
        fullscreen: true,
        overlayColor: 'rgba(0, 0, 0, 0)',
        onOpening: function () {
            /* 添加导出按钮 */
            if (!hospitalModal.find('.iziModal-header').find('.export_excel').length) {
                hospitalModal.find('.iziModal-header').append('<a class="iziModal-button export_excel" href="javascript:void(0);" onclick="exportExcel(\'#detail-modal\')" title="'+$.i18n.prop('share.sift.dc')+'"><i class="fa fa-upload"></i></a>');
            }
        },
        onOpened: function () {
            /* 设置模态框高度 */
            var height = hospitalModal.height() - hospitalModal.find('.iziModal-header').outerHeight();
            hospitalModal.find('.iziModal-content').height(height);
        }
    });

    $('#more').click(function () {
        hospitalModal.iziModal('open');
    });

    window.query = function (tag, id) {
        window.open(basePath + 'charts/hospital/overview/page?hospitalId=' + id);
    }

    // 初始化页面
    init();
});